package proxy.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import static java.lang.reflect.Proxy.newProxyInstance;

/**
 * @ClassName ProxyInvocationHandler
 * @Author Alex2
 * @Date 2025/3/20 11:10
 **/

//proxy：生成动态代理实例
//ProxyInvocationHandler：调用处理程序并返回结果
interface Rent {
    void rent();
    void signContact();
    void seeHouse();
}

class Landlord implements Rent {
    @Override
    public void rent() {
        System.out.println("房东出租房子");
    }

    @Override
    public void signContact() {
        System.out.println("中介签合同");
    }

    @Override
    public void seeHouse() {
        System.out.println("中介带你看房子");
    }
}

// 用于自动生成代理类
class ProxyInvocationHandler implements InvocationHandler {

    private Object target;  // 被代理的对象

    public void setTarget(Object target) {
        this.target = target;
    }

    //获取代理类
    public Object getProxy() {
        return newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    //处理代理实例并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ProxyUtil.method1(method.getName());
        Object invoke = method.invoke(target, args);    //动态代理的本质，反射机制实现
        ProxyUtil.method2(method.getName());
        return invoke;
    }
}

class ProxyUtil {
    public static void method1(String msg) {
        System.out.println("==========" + msg + "==========");
    }

    public static void method2(String msg) {
        System.out.println("==========" + msg + "===========");
    }
}

public class Client {
    public static void main(String[] args) {
        //真实角色
        Landlord host = new Landlord();
        //代理角色
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //设置要代理的对象
        pih.setTarget(host);
        //动态生成代理类
        Rent proxy = (Rent) pih.getProxy();
        proxy.rent();
        proxy.seeHouse();
        proxy.signContact();
    }
}